package com.durian.base.rxhttp.parse

import com.durian.base.rxhttp.exception.RxHttpResponseException
import com.google.gson.internal.`$Gson$Types`
import okhttp3.Response
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * 说明：AbstractParser
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/04/25 18:37
 * <p/>
 * 版本：version 1.0
 */
abstract class AbstractParser<T> : Parser<T> {

    protected var mType: Type

    constructor() {
        mType = getActualTypeParameter(javaClass, 0)!!
    }

    constructor(type: Type) {
        mType = `$Gson$Types`.canonicalize(type)
    }

    constructor(index:Int) : super(){
        mType = getActualTypeParameter(javaClass,index)!!
    }

    /**
     * 获取泛型类型
     *
     * @param clazz 类类型
     * @param index 第几个泛型
     * @return Type
     */
    open fun getActualTypeParameter(clazz: Class<*>, index: Int): Type? {
        val superclass = clazz.genericSuperclass as? ParameterizedType
                ?: throw RuntimeException("Missing type parameter.")
        return `$Gson$Types`.canonicalize(superclass.actualTypeArguments[index])
    }

    open fun checkResponse(response: Response) {
        if (!response.isSuccessful) {
            throw RxHttpResponseException(response = response)
        }
    }

}